<template>
  <div class="schedule-container">
    <h1 style="font-size: 30px">{{ title }}</h1>
    <div v-if="loading" class="loading jiazai">加载用户日程...</div>
    <div
        v-else
        class="schedule-scroll-view"
        ref="scrollContainer"
    >
      <div class="time-section">
        <div
            v-for="user in pastUsers"
            :key="user.patientId"
            class="schedule-item past"
            @click="showUserId(user.patientId)"
        >
          <div class="date">完成日程:{{ formattedDate(user.date) }}</div>
          <div style="width: 200px;">预约id:{{user.appointmentId}}    </div>
          <div style="width: 500px;">患者:{{user.patient_name}}</div>
          <div>点击查看患者</div>
          <div class="user-id">患者id:{{ user.patientId }}</div>
        </div>
      </div>

      <div class="today-section">
        <div
            v-for="user in todayUsers"
            :key="user.patientId"
            class="schedule-item today"
            @click="showUserId(user.patientId)"
        >
          <div class="date">今日日程:{{ formattedDate(user.date) }}</div>
          <div style="width: 200px;">预约id:{{user.appointmentId}}    </div>
          <div style="width: 500px;">患者:{{user.patient_name}}</div>
          <div>点击查看患者</div>
          <div class="user-id">患者id:{{ user.patientId }}</div>
        </div>
      </div>

      <div class="time-section">
        <div
            v-for="user in futureUsers"
            :key="user.patientId"
            class="schedule-item future"
            @click="showUserId(user.patientId)"
        >
          <div class="date">未来日程:{{ formattedDate(user.date) }}</div>
          <div style="width: 200px;">预约id:{{user.appointmentId}}    </div>
          <div style="width: 500px;">患者:{{user.patient_name}}</div>
          <div>点击查看患者</div>
          <div class="user-id">患者id:{{ user.patientId }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {mapGetters} from "vuex";
import axios from "axios";
import {ElMessage} from "element-plus";
import router from "@/router/index.js";

export default {
  data() {
    return {
      title: '智能日程视图',
      loading: true,
      users: [],
      todayRef: null
    }
  },
  computed: {
    ...mapGetters(['getUserId']), // 假设 Vuex 中存储的是
    dateGroups() {
      const today = this.getToday()
      return this.users.reduce((acc, user) => {
        const date = this.normalizeDate(user.date)
        if (date < today) acc.past.push(user)
        else if (date > today) acc.future.push(user)
        else acc.today.push(user)
        return acc
      }, { past: [], today: [], future: [] })
    },
    pastUsers() {
      return [...this.dateGroups.past].sort((a, b) =>
          new Date(b.date) - new Date(a.date))
    },
    todayUsers() {
      return this.dateGroups.today
    },
    futureUsers() {
      return [...this.dateGroups.future].sort((a, b) =>
          new Date(a.date) - new Date(b.date)
      )
    }
  },
  async mounted() {
    await this.fetchUserData()
    this.loading = false
    this.$nextTick(this.scrollToToday)
  },
  methods: {
    normalizeDate(date) {
      const d = new Date(date)
      if (isNaN(d.getTime())) {
        console.error('Invalid date:', date)
        return new Date() // 返回当前日期作为默认值
      }
      d.setHours(0, 0, 0, 0)
      return d
    },
    getToday() {
      const today = new Date()
      today.setHours(0, 0, 0, 0)
      return today
    },
    scrollToToday() {
      if (!this.todayUsers.length) return

      const container = this.$refs.scrollContainer
      const todaySection = container.querySelector('.today-section')

      if (todaySection) {
        const targetPos = todaySection.offsetTop -
            (container.clientHeight - todaySection.clientHeight) / 2

        container.scrollTo({
          top: targetPos,
          behavior: 'smooth'
        })
      }
    },
    formattedDate(date) {
      const d = new Date(date)
      if (isNaN(d.getTime())) {
        console.error('Invalid date:', date)
        return '无效日期'
      }
      return d.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      })
    },
    async showUserId(patientId) {
      alert(`当前用户ID: ${patientId}`);
      try {
        // 假设这里是你要传递的参数，你可以根据实际情况修改
        const params = {
          id: patientId, // 假设 row 中有一个 id 属性，你可以根据实际数据结构修改
          // 可以添加更多的参数
        };

        // 跳转到 home 并携带参数
        await router.push({
          path: '/escort/patient',
          query: params
        });
      } catch (error) {
        console.error("跳转失败:", error);
        ElMessage({
          message: "跳转失败，请稍后重试",
          type: "error",
          plain: true,
        });
      }
    },
    fetchUserData() {
      return new Promise(resolve => {
        setTimeout(async () => {
          const UserId = this.getUserId
          const res = await axios.get(`/api/wu_vue_2_test/Appointment/getAppointmentByUserId2?UserId=${UserId}`);
          if (res.data.code === 200) {
            console.log(res.data);
            this.users = res.data.data;
          } else {
            ElMessage.error(res.data.message);
          }
          /*this.users = [
            {patientId: '1001', date: '2024-03-15'},
            {patientId: '1002', date: '2024-03-25'},
            {patientId: '1001', date: '2024-03-15'},
            {patientId: '1002', date: '2024-03-25'},
            {patientId: '1001', date: '2024-03-15'},
            {patientId: '1002', date: '2024-03-25'},
            {patientId: '1001', date: '2024-03-15'},
            {patientId: '1002', date: '2024-03-25'},
            {patientId: '1001', date: '2024-03-15'},
            {patientId: '1001', date: '2024-03-15'},
            {patientId: '1002', date: '2024-03-25'},
            {patientId: '1001', date: '2024-03-15'},
            {patientId: '1002', date: '2024-03-25'},
            {patientId: '1001', date: '2024-03-15'},
            {patientId: '1001', date: '2024-03-15'},
            {patientId: '1002', date: '2024-03-25'},
            {patientId: '1001', date: '2024-03-15'},
            {patientId: '1002', date: '2024-03-25'},
            {patientId: '1001', date: '2024-03-15'},
            {patientId: '1001', date: '2024-03-15'},
            {patientId: '1002', date: '2024-03-25'},
            {patientId: '1001', date: '2024-03-15'},
            {patientId: '1002', date: '2024-03-25'},
            {patientId: '1001', date: '2024-03-15'},
            {patientId: '1002', date: '2024-03-25'},
            {patientId: '1003', date: new Date().toISOString().split('T')[0]}, // 确保是有效日期
            {patientId: '1004', date: '2024-04-01'},
            {patientId: '1005', date: '2028-02-28'},
            {patientId: '1002', date: '2026-03-25'}, // 有效日期
            {patientId: '1003', date: new Date().toISOString().split('T')[0]}, // 当天日期
            {patientId: '1004', date: '2024-04-01'}, // 有效日期
            {patientId: '1005', date: '2024-02-28'} // 有效日期
          ]*/
          resolve()
        }, 800)
      })
    }
  }
}
</script>

<style scoped>
.jiazai{
  margin-top: 20%;
  text-align: center;
  font-size: 20px;
  font-weight: bold;
  color: #000000;
}
.schedule-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.schedule-scroll-view {
  flex: 1;
  overflow-y: auto;
  padding: 20px 0;
  scroll-behavior: smooth;
}

.time-section {
  transition: all 0.3s;
}

.today-section {
  position: relative;
  margin: 40px 0;
  padding: 10px 0;
  background: rgba(255, 255, 255, 0.1);
}

.today-section::before {
  content: "今日日程";
  position: absolute;
  top: -30px;
  left: 20px;
  color: #666;
  font-size: 0.9em;
}

.schedule-item {
  margin: 10px 20px;
  padding: 15px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: white;
}

.schedule-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 3px 8px rgba(0, 0, 0, 0.2);
}

.schedule-item.past {
  background-color: #4CAF50;
}

.schedule-item.today {
  background-color: #FF9800;
}

.schedule-item.future {
  background-color: #2196F3;
}

.date {
  font-size: 1.1rem;
  font-weight: 500;
  margin-left: 20px;
}

.user-id {
  font-size: 0.9rem;
  opacity: 0.9;
  background: rgba(255, 255, 255, 0.15);
  padding: 4px 8px;
  border-radius: 4px;
}

@media (max-width: 768px) {
  .schedule-scroll-view {
    padding: 10px 0;
  }

  .schedule-item {
    margin: 8px 10px;
    padding: 12px;
  }

  .today-section::before {
    left: 10px;
    font-size: 0.8em;
  }
}
</style>